<?php
namespace app\faxing\channel;


use app\common\model\Gameulog;
use app\common\model\Order;
use app\common\model\Player;
use app\common\model\PlayerRole;
use app\index\controller\Exception;
use think\cache\driver\Redis;
use think\Db;
use think\facade\Log;
use think\facade\Session;
use app\common\controller\FaXingBase;

/**
 * 后台首页
 * Class Index
 * @package app\admin\controller
 */
class Wufan extends FaXingBase
{

    public function register($params)
    {

        $cid = $params['cid'];
        $sign_data = $params;
        $sign = $sign_data['sign'];
        // md5(account+fm+time+game+server+backurl+dwservId+token+loaditems+client+key)
        $str = $params['account'].$params['fm'].$params['time'].$params['game'].$params['server'].$params['backurl'].
            $params['dwservId'].$params['token'].$params['loaditems'].$params['client'];
        $str = $str . $this->extdata['Appkey'];
        $check_sign = strtoupper(md5($str));
        if($check_sign != $sign){
            $this->error("签名错误");
        }

        $account = $cid."_".$params['account'];
        $player = Player::getOne(['account'=>$account]);
        if(!$player){
            //注册
            $data['account'] = $account;
            $data['password'] = get_encrypt('123456');
            $data['type'] = 0;
            $data['cid'] = $this->cid;
            $data['gid'] = $this->gid;
            try {
                Db::startTrans();
                $player = Player::register($data);
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error("登录失败，请稍后再试。");
                Log::info("用户注册失败:".$e->getMessage());
            }
        }
        $game = $this->game;
        $data['uid'] = $player['id'];
        //记录登录信息
        Gameulog::addLog($data);
        $token = get_encrypt($data['uid']);
        $player['token'] = $token;
        unset($player['password']);
        Session::set('palyerinfo', json_encode($player));
        //redis 保存用户信息
        $redis = new Redis();
        $redis->set($token, $player);
        if (strpos($game['api_login_url'], '?') !== false) {
            $game_url = $game['api_login_url']."&token=".$token;
        } else {
            $game_url = $game['api_login_url']."?token=".$token;
        }
        return ['game_url'=>$game_url,'token'=>$token];
    }
    public function order($order)
    {
        $game_name = get_game_filed($order['gid'],'name');
        $role = PlayerRole::where(['gid'=>$order['gid'],'uid'=>$order['uid'],'cid'=>$order['cid']])->find();


        $account = get_player($order['uid'],'account');
        $account = explode("_",$account);
        $sign = get_sign(['order_no'=>$order['order_no']],$this->extdata['Paykey']); // 回传验证
        $data = [
            'game_name'=>$game_name,//游戏名称
            'server_id'=>'s1',//区服id
            'server_name'=>'s1',//区服名称
            'role_id'=>$role['role_id'] ?? 0,//角色id
            'role_name'=>$role['role_name'] ?? "",//角色名称
            'item_id'=>rand(000000,999999),//商品id
            'item_name'=>$order['goods_name'],//商品名称
            'account'=>$account[1],//商品名称
            'amount'=>(int) $order['amount'],//金额 整数：元
            'cparam' => $order['order_no']."|".$sign,
            'recharge_type'=>'default',
            'recharge_style'=>'xx',
            'extra'=> get_sign(['order_no'=>$order['order_no']],$this->extdata['Paykey']) // 回传验证
        ];
        return $data;
    }

    public function check_order($params)
    {
        $order_no = $params['cparam'];
        if(stripos($params['cparam'],"|") !== false){
            $ord_arr = explode("|",$params['cparam']);
            $order_no = $ord_arr[0];
            $sign = $ord_arr[1];

            // 双重校验
            $order_sign = get_sign(['order_no'=>$order_no],$this->extdata['Paykey']);

            if($order_sign != $sign){
                echo json_encode(['status'=>-11,'message'=>'签名错误']);exit;
            }
        }

        // 查询订单
        $order = Order::where([
            'order_no'=>$order_no
        ])->find();

        if(!$this->check_sign($params,$this->extdata['Paykey'])){
            echo json_encode(['status'=>-11,'message'=>'签名错误']);exit;
        }


        if($order['amount'] != $params['rmb']){
            echo json_encode(['status'=>-11,'message'=>'金额错误']);exit;
        }
        $order->trade_no = $params['orderid'];
        $order->save();

        return $order;
    }

    public function message($message,$order)
    {
        $account = get_player($order['uid'],'account');
        $account = explode("_",$account);
        echo $message === 'success' ? json_encode(['code'=>1,'message'=>'成功','data'=>['orderid'=>$order['trade_no'],'account'=>$account[1],'rmb'=>(int) $order['amount']]]) :  json_encode(['status'=>100,'message'=>'未知错误']);
        exit;
    }

    protected function check_sign($params, $key)
    {
        // MD5编码（小写）sign = md5(account+orderid+rmb+num+type+time+game+server+role+itemid+price+cparam+密钥)，里面的参数不用进行编码。 签名的密钥游戏方自定义
        $str = $params['account'].$params['orderid'].$params['rmb'].$params['num'].$params['type'].
            $params['time'].$params['game'].$params['server'].$params['role'].$params['itemid'].$params['price'].$params['cparam'].$key;
        $check_sign = md5($str);
        $sign = $params['sign'];
        unset($params['sign']);
        if($check_sign != $sign){
            return false;
        }
        return true;
    }

}